package common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class ImageDownloader {
    public static File urlToFile(String imageUrl) throws Exception {
        // 打开 URL 连接并下载文件
        URL url = new URL(imageUrl);
        try (InputStream in = url.openStream()) {
            // 创建一个临时文件
            File tempFile = File.createTempFile("image-", ".jpg");
            // 使用 FileOutputStream 写入文件
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            return tempFile; // 返回下载后的临时文件
        }
    }

    public static void main(String[] args) {
        String imageUrl = "https://oss.h-ksg.com/ksg_qxImg20250610140053850629.jpg";
        try {
            File imageFile = urlToFile(imageUrl);
            System.out.println("文件保存路径: " + imageFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
